package com.foo.common.utils.http;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通用http发送方法
 *
 * @author foo
 */
public class HttpUtils
{
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public static String sendRequest(String url, JSONObject requestBody, Map<String, String> headers, String method) {
        try {
            if (requestBody != null && !requestBody.isEmpty() && method.equals("GET")) {
                // 构建带查询参数的URL
                StringBuilder urlBuilder = new StringBuilder(url);
                urlBuilder.append("?");
                for (Map.Entry<String, Object> entry : requestBody.entrySet()) {
                    if (null != entry.getValue()) {
                        urlBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                                .append("=")
                                .append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"))
                                .append("&");
                    }
                }
                url = urlBuilder.toString();
                if (url.endsWith("&")) {
                    url = url.substring(0, url.length() - 1);
                }
            }

            // 创建URL对象并打开连接
            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

            // 设置请求方法
            connection.setRequestMethod(method);

            // 设置请求头参数
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // 发送POST请求时写入请求体
            if (method.equals("POST")) {
               if(requestBody != null && !requestBody.isEmpty()){
                    connection.setDoOutput(true);
                    connection.getOutputStream().write(requestBody.toString().getBytes(StandardCharsets.UTF_8));
               }
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();

            // 处理重定向
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String newUrl = connection.getHeaderField("Location");
                connection = (HttpURLConnection) new URL(newUrl).openConnection();
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
                responseCode = connection.getResponseCode();
            }

            BufferedReader reader;
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));
            }

            // 读取响应内容
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null; // 或者抛出自定义异常
        }
    }
}
